package com.xyy.saas.payment.callback.core.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.cores.api.PaymentOpenAccountApi;
import com.xyy.saas.payment.cores.bo.jd.JDBankCardBindDto;
import com.xyy.saas.payment.cores.enums.JDPayContractStatusEnum;
import com.xyy.saas.payment.cores.enums.JDPayContractTypeEnum;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.vo.ResultVO;
import com.xyy.saas.payment.cores.vo.jd.JDQueryOneKeySignResultVo;
import com.xyy.saas.payment.dao.model.BankCardBind;
import com.xyy.saas.payment.service.BankCardBindService;
import com.xyy.saas.payment.util.LeafUtil;
import com.xyy.saas.payment.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 京东支付协议签约定时处理签约中数据
 */
@Slf4j
@ElasticJobConf(name = "com.xyy.saas.payment.callback.core.job.jdPayContractJob", cron = "0 0/1 * * * ?")
public class JDPayContractJob implements SimpleJob {
    @Autowired
    private LeafUtil leafUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private BankCardBindService bankCardBindService;
    @Resource
    private PaymentOpenAccountApi paymentOpenAccountApi;

    @Override
    public void execute(ShardingContext shardingContext) {
        long startTime = System.currentTimeMillis();
        log.info("JDPayContractJob#execute start.");
        boolean lockSucc = false;
        String lockKey = RedisUtil.JD_PAY_PREFIX + "JDPayContractJob";
        try {
            if (!redisUtil.tryLock(lockKey, 60 * 10)) {
                log.info("JDPayContractJob 未获取到分布式锁，不进行处理");
                return;
            }
            lockSucc = true;
            List<BankCardBind> procBankCards = bankCardBindService.queryProc();
            if (CollectionUtils.isEmpty(procBankCards)) {
                log.info("JDPayContractJob 无签约中数据，不进行处理");
                return;
            }
            for (BankCardBind procBankCard : procBankCards) {
                dealProc(procBankCard);
            }
        } catch (Exception e){
            log.error("JDPayContractJob#execute error : ", e);
        } finally {
            log.info("JDPayContractJob#execute end. cost={}ms", (System.currentTimeMillis() - startTime));
            if (lockSucc) {
                redisUtil.unLock(lockKey);
            }
        }
    }

    private void dealProc(BankCardBind procBankCard) {
        procBankCard.setYn("N");
        // 对于协议签约数据不做查询处理
        if (procBankCard.getContractType().equals(JDPayContractTypeEnum.CONTRACTSIGN.getCode())) {
            log.info("JDPayContractJob 置为失效：协议签约 {}", procBankCard);
            bankCardBindService.update(procBankCard);
            return;
        }
        // 对一键签约数据，先调用接口查询一次，若仍为处理中，则更新为失效
        JDQueryOneKeySignResultVo jdQueryOneKeySignResultVo = JDQueryOneKeySignResultVo.builder().businessReqNo(leafUtil.getSnowflakeId()).merchantNo(procBankCard.getMerchantNo()).requestNo(procBankCard.getReqNo()).sync(true).build();
        log.info("JDPayContractJob 发起查询请求 : {}", procBankCard);
        ResultVO<JDBankCardBindDto> resultVO = paymentOpenAccountApi.queryOneKeySignResult(jdQueryOneKeySignResultVo);
        log.info("JDPayContractJob 响应数据 : {} {} ", jdQueryOneKeySignResultVo.getBusinessReqNo(), resultVO);
        // 若调用失败或者状态为签约中，则置为失效
        if (!ResultCodeEnum.SUCCESS.getCode().equals(resultVO.getCode()) || resultVO.getResult().getContractStatus().equals(JDPayContractStatusEnum.PROC.getCode())) {
            log.info("JDPayContractJob 置为失效：一键签约 {}", procBankCard);
            bankCardBindService.update(procBankCard);
        }
    }

}
